<template>
  <view>
    <view class="my-config">

      <view class="config-item" @click="navigateTo('username')">
        <view>更改名字</view>
        <view class="mark"> > </view>
      </view>

      <view class="config-item" @click="navigateTo('sex')">
        <view>性别</view>
        <view class="mark">{{ selectedSex }} > </view>
      </view>

      <view class="config-item">
        <view>生日</view>
        <view class="mark">{{ userInfo.birthday || '未设置' }} > </view>
      </view>

      <view class="config-item">
        <view>绑定手机号</view>
        <view class="mark">{{ userInfo.phone || '未绑定' }} > </view>
      </view>

      <view class="exit" @click="logout">退出</view>

    </view>
  </view>
</template>

<script>
import $http from '@/api/request.js'
import { mapActions } from 'vuex'

export default {
    data() {
        return {
            selectedSex: '未选择' // 或者从本地缓存读取
        };
    },
    computed: {
        userInfo() {
            return this.$store.state.user.userInfo;
        }
    },
    onShow() {
        // 调用 Vuex 的 fetchUserInfo 方法获取用户信息
        this.fetchUserInfo(this.userInfo.phone);

        // 动态更新性别显示
        const sexMap = { M: '男', F: '女' };
        this.selectedSex = sexMap[this.userInfo.sex] || '未选择';
    },
    methods: {
        ...mapActions(['fetchUserInfo']),
        navigateTo(page) {
            let url = '';
            switch (page) {
                case 'username':
                    url = '/pages/tabbar/tabbar-5-detail/userinfo-detail/username'; // 替换为实际路径
                    break;
                case 'sex':
                    url = '/pages/tabbar/tabbar-5-detail/userinfo-detail/sex';
                    break;
                default:
                    return;
            }
            uni.navigateTo({
                url: url
            });
        },
        logout() {
            // 调用 Vuex 的 logout mutation，将 loginStatus 设置为 false
            this.$store.commit('logout');
            // 返回首页或执行其他逻辑
            uni.switchTab({
                url: '/pages/tabbar/tabbar-5/tabbar-5'
            });
        },
        updateSex(sex) {
            this.selectedSex = sex;
            uni.setStorageSync('userSex', sex); // 每次更新也同步到本地
        },
    },
    mounted() {
        // 监听事件
        uni.$on('update-sex', this.updateSex);
    },
    beforeDestroy() {
        // 防止重复绑定或内存泄漏
        uni.$off('update-sex', this.updateSex);
    }
}
</script>

<style lang="scss">
page {
  background-color: #eaeaea; /* 页面整体底色 */
}

.config-item{
  background-color: white;
  display: flex;
  justify-content: space-between;
  padding: 20rpx 0 20rpx 20rpx;
  border-bottom: 2rpx solid lightgray;
  margin-top: 5rpx;
  font-weight: bold;
}
.mark{
  padding-right: 20rpx;
}
.exit{
  background-color: rgba(0, 255, 21, 0.44);
  width: 100%;
  line-height: 80rpx;
  text-align: center;
  margin-top: 15rpx;
}

</style>
